var player = require('../../../playermanager/daifugo/game/DaifugoPlayer');
var log4js = require('log4js');
var logger = log4js.getLogger('SocketController');
var uuid = require('uuid');
var config = require('../config');
var Session = require("../../common/controllers/session");
var cookie = require('cookie');
var cookieParser = require('cookie-parser');
var PlatForm = require('../../common/controllers/pfapi');

/*
*       @function create new socket controller
* */
function SocketController(app) {
    logger.trace('enter constructor');
    SocketController.app = app;
}
module.exports = SocketController;

SocketController.prototype.init = function (io) {
    logger.trace('enter init');
    // verify session
    //io.use(this.authorizeConnection);

    // listen for clients
    io.on('connection', function (socket) {
        // Init the platform with user's information
        var session = socket.request.session;
        //var user = session.auth.user;
        //var platform = new PlatForm(config, user.access_token, user.refresh_token);

        logger.trace('new connection arrived ');
        socket.player = new player.Player(1, config.common, session);
        socket.player.initWithSocket(socket, function (result) {
            if (result === true) {
                logger.info('connection established');
            } else {
                logger.error('connection not established');
            }
        });
    });
};

/**
 * Perform authorization on a new connection
 */
SocketController.prototype.authorizeConnection = function(socket, next) {
    var data = socket.request;
    if (data.headers === undefined || (data.headers && data.headers.cookie === undefined)) {
        logger.error("[authorizeConnection] Get cookie failed !");
        next(new Error('Login required'));
        return;
    }

    logger.debug(data.headers.cookie);
    try {
        var signedCookies = cookie.parse(data.headers.cookie);
        var cookies = cookieParser.signedCookies(signedCookies, config.SESSION_SECRET);

        data.sessionID = cookies['connect.sid'];
        data.sessionStore = SocketController.app.sessionStore;
        logger.trace("[authorizeConnection] sessionID = " + data.sessionID);

        data.sessionStore.get(data.sessionID, function (err, session) {
            if (err || !session || !session.auth || !session.auth.loggedIn) {
                logger.error("[authorizeConnection] Grab session failed !");
                logger.error(err);
                // if we cannot grab a session, turn down the connection
                next(new Error('Login required'));
            } else {
                // save the session data and accept the connection
                logger.debug(session);
                data.session = new Session.Session(data, session); // must create new Session object to reuse later
                next();
            }
        });
    } catch (ex) {
        logger.error(ex);
        next(new Error('Login required'));
    }
};
